/*
 * IMonaBoardReader.java
 *
 * Created on 2007/03/27 +0900
 *
 * $Revision: 38 $
 * $Date: 2008-10-11 08:48:45 +0000 (Sat, 11 Oct 2008) $
 */

package org.gikolet.bbs.imona.reader;

import java.io.IOException;
import java.util.Vector;

import org.gikolet.bbs.data.Bbs;
import org.gikolet.bbs.data.Board;
import org.gikolet.bbs.data.BoardList;
import org.gikolet.bbs.imona.IMonaProperties;
import org.gikolet.bbs.reader.BoardReader;
import org.gikolet.framework.util.NullProgressMonitor;
import org.gikolet.framework.util.ProgressMonitor;
import org.gikolet.framework.util.StringUtilities;

/**
 * @author Tetsutaro (latest modification by $Author: tetsutaro.ss $)
 * @version $Revision: 38 $ $Date: 2008-10-11 08:48:45 +0000 (Sat, 11 Oct 2008) $
 */
public class IMonaBoardReader extends AbstractIMonaReader implements BoardReader {
    public IMonaBoardReader(IMonaProperties properties) {
	super(properties);
    }

    public IMonaBoardReader(IMonaProperties properties, int bufferSize) {
	super(properties, bufferSize);
    }

    public void read(Bbs bbs, BoardList boardList, ProgressMonitor progressMonitor)
	    throws IOException {
	if (progressMonitor == null) {
	    progressMonitor = NullProgressMonitor.INSTANCE;
	}

	String request = "m=b";
	byte[] bytes = read(request, progressMonitor);

	ReaderUtilities.errorChack(bytes[0]);

	int startOff = 0;
	for (int i = 0; i < bytes.length; i++) {
	    if (bytes[i] == 0x0A) {
		startOff = i + 1;
		break;
	    }
	}
	String data = ReaderUtilities.toString(bytes, startOff, bytes.length - startOff);

	String[] strs = StringUtilities.tokenToStrings(data, "\n");

	data = null;
	bytes = null;
	System.gc();

	Vector categories = new Vector();

	int i = 0;
	// カテゴリ名の取得
	while (i < strs.length && !strs[i].equals("")) {
	    categories.addElement(strs[i]);
	    i++;
	}
	i++;

	BoardList newBoardList = new BoardList();

	// カテゴリと板名からBBSBoardを作る
	int categoryIndex = 0; // カテゴリのインデックス

	while (i < strs.length && !categories.isEmpty()) {
	    String category = (String) categories.firstElement();
	    categories.removeElement(category);

	    String[] boardNames = StringUtilities.tokenToStrings(strs[i++], "\t");
	    String[] boardNos = StringUtilities.tokenToStrings(strs[i++], "\t");

	    for (int j = 0; j < boardNames.length; j++) {
		Board newBoard = new Board(bbs, boardNos[j], boardNames[j]);

		newBoardList.addBoard(category, newBoard);
	    }
	    categoryIndex++;
	}

	if (newBoardList.getCategoryCount() == 0) {
	    throw new IOException("Category is not found.");
	}
	boardList.addBoards(newBoardList);
    }
}
